<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useNaiveForm } from '@/hooks/common/form';
import { fetchAddDept, fetchGetDeptTree, fetchUpdateDept } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';
import UserSelectModal from './user-select-modal.vue';

defineOptions({
  name: 'DeptOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Dept | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.dept.addDept'),
    edit: $t('page.manage.dept.editDept')
  };
  return titles[props.operateType];
});

type Model = {
  deptId: string;
  deptName: string;
  deptCode: string;
  parentId: number | null;
  status: Api.Common.EnableStatus;
  managerName: string;
  managerId?: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    deptId: '',
    deptName: '',
    deptCode: '',
    parentId: null,
    status: 1,
    managerName: '',
    managerId: null
  };
}

// 表单校验规则
const rules = {
  deptName: [
    {
      required: true,
      message: $t('page.manage.dept.form.deptName'),
      trigger: ['input', 'blur']
    }
  ]
};

const deptTreeOptions = ref();

// 用户选择弹窗的可见性
const userSelectModalVisible = ref(false);

// 当前选中的用户
const currentSelectedUser = ref<Api.SystemManage.User | null>(null);

async function getDeptTreeOptions() {
  const { error, data } = await fetchGetDeptTree();

  if (!error) {
    deptTreeOptions.value = [...data];
  }
}

// 打开用户选择弹窗
function handleSelectManager() {
  userSelectModalVisible.value = true;
}

// 处理用户选择确认
function handleUserSelectConfirm(user: Api.SystemManage.User | null) {
  currentSelectedUser.value = user;
  model.managerName = user?.displayName || user?.userName || '';
  model.managerId = user?.id || null;
}

// 清除负责人
function handleClearManager() {
  currentSelectedUser.value = null;
  model.managerName = '';
  model.managerId = null;
}

function handleInitModel() {
  // 重置为默认值
  const defaultModel = createDefaultModel();
  model.deptId = defaultModel.deptId;
  model.deptName = defaultModel.deptName;
  model.deptCode = defaultModel.deptCode;
  model.parentId = defaultModel.parentId;
  model.status = defaultModel.status;
  model.managerName = defaultModel.managerName;
  model.managerId = defaultModel.managerId;

  // 重置当前选中的用户
  currentSelectedUser.value = null;

  if (props.operateType === 'edit' && props.rowData) {
    // 编辑模式下，逐个赋值确保响应式
    model.deptId = props.rowData.deptId?.toString() || '';
    model.deptName = props.rowData.deptName || '';
    model.deptCode = props.rowData.deptCode || '';
    model.parentId = props.rowData.parentId || null;
    model.status = props.rowData.status ?? 1;
    model.managerName = props.rowData.managerName || '';
    model.managerId = props.rowData.managerId || null;

    // 如果有负责人信息，创建用户对象用于选择弹窗
    if (props.rowData.managerId && props.rowData.managerName) {
      currentSelectedUser.value = {
        id: props.rowData.managerId,
        userName: props.rowData.managerName,
        loginName: props.rowData.managerName,
        nickName: props.rowData.managerName,
        displayName: props.rowData.managerName,
        address: '',
        age: '',
        gender: null,
        idNumber: '',
        birthday: '',
        telephone: '',
        email: '',
        userRoles: [],
        status: 1,
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      };
    }
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  try {
    // 准备提交的数据，转换字段类型
    const submitData = {
      ...model,
      deptId: Number(model.deptId) || 0
    };

    let result;
    if (props.operateType === 'add') {
      result = await fetchAddDept(submitData as Api.SystemManage.Dept);
    } else {
      result = await fetchUpdateDept(submitData as Api.SystemManage.Dept);
    }

    if (!result.error) {
      const successMessage = props.operateType === 'add' ? $t('common.addSuccess') : $t('common.updateSuccess');
      window.$message?.success(successMessage);
      closeModal();
      emit('submitted');
    }
  } catch (error) {
    window.$message?.error($t('common.operationFailed'));
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    getDeptTreeOptions();
    restoreValidation();
  }
});

// 监听 rowData 变化，确保切换不同部门时数据能正确更新
watch(
  () => props.rowData,
  newRowData => {
    if (visible.value && newRowData) {
      handleInitModel();
    }
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <NModal v-model:show="visible" preset="dialog" :title="title" style="width: 1000px; max-width: 90vw">
    <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
      <NGrid :cols="2" :x-gap="16">
        <NFormItemGi :label="$t('page.manage.dept.deptId')" path="deptId">
          <NInput v-model:value="model.deptId" :placeholder="$t('page.manage.dept.form.deptId')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.dept.deptName')" path="deptName">
          <NInput v-model:value="model.deptName" :placeholder="$t('page.manage.dept.form.deptName')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.dept.deptCode')" path="deptCode">
          <NInput v-model:value="model.deptCode" :placeholder="$t('page.manage.dept.form.deptCode')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.dept.parentDept')" path="parentId">
          <NTreeSelect
            v-model:value="model.parentId"
            :options="deptTreeOptions"
            :placeholder="$t('page.manage.dept.form.parentDept')"
            clearable
            filterable
            show-path
            separator=" / "
            key-field="deptId"
            label-field="deptName"
            children-field="children"
          />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.dept.managerName')" path="managerId">
          <div class="flex items-center gap-8px">
            <NInput v-model:value="model.managerName" :placeholder="$t('page.manage.dept.form.manager')" readonly />
            <NButton type="primary" @click="handleSelectManager">
              {{ $t('page.manage.dept.selectManager') }}
            </NButton>
            <NButton v-if="model.managerName" @click="handleClearManager">
              {{ $t('common.clear') }}
            </NButton>
          </div>
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.dept.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItemGi>
      </NGrid>
    </NForm>

    <template #action>
      <NSpace>
        <NButton @click="closeModal">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>

    <!-- 用户选择弹窗 -->
    <UserSelectModal
      v-model:visible="userSelectModalVisible"
      :selected-user="currentSelectedUser"
      @confirm="handleUserSelectConfirm"
    />
  </NModal>
</template>

<style scoped></style>
